package com.enjoyor.soa.traffic.util.base;

import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

public class UUIDUtil {

    private static boolean IS_THREADLOCALRANDOM_AVAILABLE = false;
    private static Random random;
    private static final long leastSigBits;

    static {
        try {
            IS_THREADLOCALRANDOM_AVAILABLE = null != UUIDUtil.class.getClassLoader()
                    .loadClass("java.util.concurrent.ThreadLocalRandom");
        } catch (ClassNotFoundException localClassNotFoundException) {
        }
        byte[] seed = new SecureRandom().generateSeed(8);
        leastSigBits = new BigInteger(seed).longValue();
        if (!IS_THREADLOCALRANDOM_AVAILABLE) {
            random = new Random(leastSigBits);
        }
    }

    public static String random() {
        byte[] randomBytes = new byte[16];
        if (IS_THREADLOCALRANDOM_AVAILABLE) {
            ThreadLocalRandom.current().nextBytes(randomBytes);
        } else {
            random.nextBytes(randomBytes);
        }
        long mostSigBits = 0L;
        for (int i = 0; i < 8; i++) {
            mostSigBits = mostSigBits << 8 | randomBytes[i] & 0xFF;
        }
        long leastSigBits = 0L;
        for (int i = 8; i < 16; i++) {
            leastSigBits = leastSigBits << 8 | randomBytes[i] & 0xFF;
        }
        return new UUID(mostSigBits, leastSigBits).toString().replaceAll("-", "");
    }

    public static void main(String[] args) {
        System.out.println(random());
        System.out.println(random().length());
    }

}
